import pandas
import pandas as pd
import geopandas as geo
import matplotlib.pyplot as plt
from math import cos, sin, atan2, sqrt, pi ,radians, degrees

# pandas显示所有行
pd.set_option('display.max_rows', None)
# 设置pandas显示的列数
pd.set_option('display.max_columns', 20)
# 让dataframe打印不换行
pd.set_option('display.width', 5000)

# 设置画板
fig = plt.figure(1, (16, 9), dpi=120)
ax = plt.subplot(111)
plt.sca(ax)


def center_geolocation(geolocations):
    x = 0
    y = 0
    z = 0
    lenth = len(geolocations)
    for lon, lat in geolocations:
        lon = radians(float(lon))
        lat = radians(float(lat))

        x += cos(lat) * cos(lon)
        y += cos(lat) * sin(lon)
        z += sin(lat)

    x = float(x / lenth)
    y = float(y / lenth)
    z = float(z / lenth)

    return (degrees(atan2(y, x)), degrees(atan2(z, sqrt(x * x + y * y))))

# read the zip site location file
# zip = pd.read_csv('./zipCar/zipcar_site.csv')
# print(zip.shape)
# print(zip.head(1))
# zip = geo.GeoDataFrame(zip, geometry=geo.points_from_xy(zip.lat, zip.lon))
# print(zip.shape)
# print(zip.head(1))
zip = geo.read_file('E:\DataSet\zipcar_now\zip.shp')
print(zip.shape)
zip = zip.drop(zip[zip.carSize==0].index)
print(zip.shape)
# zip.to_file('E:\DataSet\zipcar_now\zip.shp',index=False)
# zip.to_file('E:\DataSet\zipcar_now\zipnow.shp',index=False)

# draw the zip site distribution to the artboard
zip.plot(ax=ax, edgecolor=(0, 0, 0, 1), facecolor=(1, 0, 0, 1), linewidths=0, markersize=10)

# read newYork map
map = geo.read_file('../data/map/NewYork.shp')
# draw newyork map to artboard
map.plot(ax=ax, edgecolor=(0, 0, 0, 1), facecolor=(0, 0, 0, 0), linewidths=0.5)

# metro = geo.read_file('./subway/geo_export_1f65c7c2-484d-4d0d-bd10-27511e9967c2.shp')
# metro.plot(ax=ax, edgecolor=(0, 0, 0, 1), facecolor=(0, 1, 1, 1), linewidths=0, markersize=5)

grid = geo.read_file('E:\DataSet\zipcar_now\grid.shp')
print(grid.shape)
grid.plot(ax=ax, edgecolor=(0, 0, 0, 1), facecolor=(0, 0, 0, 0), linewidths=0.5)

# read grid file
point_grid = geo.read_file('E:\DataSet\zipcar_now\point_grid.shp')
print(point_grid.head())
# draw grid to artboard
grid.plot(ax=ax, edgecolor=(0, 0, 0, 1), facecolor=(0, 0, 0, 0), linewidths=0.5)

# 求交集
# grid = grid[grid.intersects(zip.unary_union)]
# print(grid.shape)
# grid.plot(ax=ax, edgecolor=(0, 0, 0, 1), facecolor=(0, 0, 0, 0), linewidths=0.5)
# print(grid.head())
# grid.to_file('E:\DataSet\zipcar_now\grid.shp',index=False)
# plt.show()

# read files where grid and sites overlap
# grid_point = geo.read_file('E:\DataSet\zipcar_now\grid.shp')
# grid_point.plot(ax=ax, edgecolor=(0, 0, 0, 1), facecolor=(1, 0, 0, 1), linewidths=0, markersize=20)
# print(grid_point.head())

# get new grid file,delete duplicate rows from grid files
# new_grid = grid_point[['id', 'left', 'top', 'right', 'bottom']].drop_duplicates(keep='first').copy()
# print(new_grid.shape)
# print(new_grid.head())

# group sites by grid
groupSiteByGrid = point_grid.groupby(['id'])
print(groupSiteByGrid)
# zip_centroids_id = ['id','CS_Spaces','x','y']
ids = []
carSize = []
lon = []
lat = []

for name,group in groupSiteByGrid:
    # ids.append(name)
    # print(group)
    points = []
    temp_id = 0
    temp_space = 0
    # print(group)
    for index, row in group.iterrows():
        coordinate = []
        coordinate.append(row.lat)
        coordinate.append(row.lon)
        points.append(coordinate)
        temp_id = row.id
        temp_space += row.carSize
    center_tuple = center_geolocation(points)
    lon.append(center_tuple[0])   # return (-73.78509245732995, 40.712174305836356) tuple
    lat.append(center_tuple[1])   # return (-73.78509245732995, 40.712174305836356) tuple
    ids.append(temp_id)
    carSize.append(temp_space)
    # print(temp_id,temp_space)
# draw center_point
plt.scatter(lon,lat,marker='o',s=5, c='blue')
# test_grid = grid[grid.intersects(grid_point.unary_union)]
# print('------------test_grid------------')
# print(test_grid.head())
# print(test_grid.shape,type(test_grid))
# test_grid.plot(ax=ax, edgecolor=(0, 0, 0, 1), facecolor=(0, 0, 0, 0), linewidths=0.5)
# test_grid.to_file('E:/DataSet/zipcar_now/grid_zip.shp',index=False)

# build grid site dataframe
site_dataframe = pandas.DataFrame({'id':ids,'carSize':carSize,'lon':lon,'lat':lat})
print(site_dataframe.head())
print(site_dataframe.shape)
site_size = site_dataframe['carSize'].tolist()
print(site_size)
print('车辆总数:',site_dataframe['carSize'].sum())
# site_dataframe.to_csv('E:/DataSet/zipcar_now/site_merge_center.csv',index=False)
plt.scatter(site_dataframe['lon'],site_dataframe['lat'],marker='^',s=2, c='blue')
print(sum(site_dataframe['carSize'].tolist()))

# print([i*2 for i in site_size])
# new_site_size = [int(i*2*0.7) for i in site_size]
# print(new_site_size)
# print(sum(new_site_size))
# site_dataframe['car_size'] = new_site_size
# site_dataframe['CS_Spaces'] = site_dataframe['CS_Spaces']*2
# site_dataframe.to_csv('E:/DataSet/test_site.csv',index=False)
# print(site_dataframe.head())
# print()
plt.show()
